﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Models.Models.Sugar;
using Services.Base;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace HandyWpf.ViewModels.Base
{
    /// <summary>
    /// 只包含查询操作的ViewModel
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <typeparam name="TQuery">查询实体</typeparam>
    /// <typeparam name="IBaseService">数据服务</typeparam>
    public abstract partial class BasePagedViewModel<T,TQuery,IBaseService>: ObservableObject
        where TQuery:ObservableObject,new()
        where T : class,new()
        where IBaseService:IBaseService<T>
    {
        protected IBaseService<T> baseService;
        public BasePagedViewModel(IBaseService<T> baseService)
        {
            this.baseService = baseService;
        }
        /// <summary>
        /// 页码
        /// </summary>
        [ObservableProperty]
        private int page = 1;
        /// <summary>
        /// 每页条数
        /// </summary>
        [ObservableProperty]
        private int limit = 10;
        /// <summary>
        /// 总页数
        /// </summary>
        [ObservableProperty]
        private int totalPage = 1;
        /// <summary>
        /// 查询模型实体
        /// </summary>
        [ObservableProperty]
        private TQuery query = new();
        /// <summary>
        /// DataGrid的source
        /// </summary>
        [ObservableProperty]
        private ObservableCollection<T> list = new();
        /// <summary>
        /// 每个子类需要实现此方法，获取当前页面的查询条件
        /// </summary>
        /// <returns></returns>
        public abstract Expression<Func<T,bool>> GetQueryExpression();
        /// <summary>
        /// 每个子类需要实现此方法，获取当前页面数据的排序条件
        /// </summary>
        /// <returns></returns>
        public abstract (Expression<Func<T, object>>, OrderByType)? GetOrderByExpression();
        /// <summary>
        /// 获取页面显示数据的默认实现，可重写
        /// </summary>
        [RelayCommand]
        public virtual void GetList()
        {
            var order = GetOrderByExpression();
            PageModel<T>? pageModel;
            if (order != null)
            {
                pageModel = baseService.GetPaged(GetQueryExpression(), order.Value.Item1,order.Value.Item2, Page, Limit);
            }
            else
            {
                pageModel = baseService.GetPaged(GetQueryExpression(), Page, Limit);
            }
            TotalPage=(int)Math.Ceiling((double)pageModel.Total / Limit);
            List.Clear();
            pageModel.Data.ForEach(x => List.Add(x));
        }

    }
}
